<template>
  <Dialog :title="t('interview.index.setGroup')" v-model="dialogVisible" width="1400">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item>
        <el-button type="primary" plain @click="handleAddGroup">
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <vxe-table
      id="iInterviewGroup-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('interviewGroup.fields.groupName')"
        field="groupName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.meetingNumber')"
        field="meetingNumber"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.meetingPassword')"
        field="meetingPassword"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.qqGroupNumber')"
        field="qqGroupNumber"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.specialistId1')"
        field="specialistName1"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.specialistId2')"
        field="specialistName2"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('interviewGroup.fields.specialistId3')"
        field="specialistName3"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="140"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['recruit:interview:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['recruit:interview:delete']"
          >
            {{ t('action.delete') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </Dialog>

  <!-- 第一步 勾选当天学生 -->
  <RecruitStudentSelect ref="step1Ref" @next="handleStudentSelected" />
  <!-- 第二步 表单弹窗：添加/修改 -->
  <InterviewGroupFormStep2
    v-if="currentInterview"
    ref="step2Ref"
    :interview-info="currentInterview"
    @next="handleGroupInfoFilled"
  />
  <!-- 第三步 设置学生的Slot -->
  <RecruitStudentSetSlotStep3
    v-if="currentInterview"
    ref="step3Ref"
    :interview-info="currentInterview"
    @next="handleFinish"
  />
</template>

<script setup lang="ts">
import {
  InterviewGroupApi,
  InterviewGroupVO,
  InterviewGroupWithStudentSlotsSaveReqVO
} from '@/api/recruit/interviewgroup'
import InterviewGroupFormStep2 from './InterviewGroupFormStep2.vue'
import type { VxeTableInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import RecruitStudentSelect from '@/views/recruit/recruitstudent/components/RecruitStudentSelect.vue'
import { InterviewApi, InterviewVO } from '@/api/recruit/interview'
import { StudentApi, StudentVO } from '@/api/recruit/recruitstudent'
import RecruitStudentSetSlotStep3 from '@/views/recruit/interviewgroup/components/RecruitStudentSetSlotStep3.vue'

/** 面试分组 列表 */
defineOptions({ name: 'InterviewGroupList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const tableRef = ref<VxeTableInstance>()
const step1Ref = ref<InstanceType<typeof RecruitStudentSelect>>()

const loading = ref(true) // 列表的加载中
const list = ref<InterviewGroupVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const advancedSearching = ref(false) // 高级搜索
const dialogVisible = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  advanced: undefined,
  batchId: undefined,
  interviewId: undefined,
  groupName: undefined,
  meetingNumber: undefined,
  meetingPassword: undefined,
  qqGroupNumber: undefined,
  specialistId1: undefined,
  specialistId2: undefined,
  specialistId3: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const currentInterviewId = ref('')

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InterviewGroupApi.getInterviewGroupPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  advancedSearching.value = false
  ;(queryParams as any).advanced = undefined
  queryParams.interviewId = currentInterviewId.value
  handleQuery()
}

/** 添加/修改操作 */
const step2Ref = ref<InstanceType<typeof InterviewGroupFormStep2>>()
const openForm = async (type: string, id?: string) => {
  step2Ref.value?.open(type, id)
  if (type === 'update' && id) {
    // 更新逻辑 从库里读取这个分组有哪些学生
    students.value = await StudentApi.getStudentByGroupId(id)
  }
}

const step3Ref = ref<InstanceType<typeof RecruitStudentSetSlotStep3>>()

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InterviewGroupApi.deleteInterviewGroup(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 新增分组 弹出选择学生弹窗
const handleAddGroup = () => {
  if (currentInterview.value) {
    step1Ref.value?.open(currentInterview.value)
  }
}

const currentInterview = ref<InterviewVO>()
// 获取当前面试信息
const getInterview = async () => {
  currentInterview.value = await InterviewApi.getInterview(currentInterviewId.value)
}

// 面试管理-设置分组 打开某一个面试的分组弹窗
const show = async (interviewId: string) => {
  currentInterviewId.value = interviewId
  dialogVisible.value = true
  await nextTick()
  resetQuery()
  await getInterview()
}

const students = ref<StudentVO[]>([])

// 学生选择了之后 处理下一步
const handleStudentSelected = (value: StudentVO[]) => {
  students.value = value
  openForm('create')
}

const interviewGroup = ref<InterviewGroupVO>()
// 分组信息填写完毕 处理下一步
const handleGroupInfoFilled = async (value: InterviewGroupVO) => {
  interviewGroup.value = value
  step3Ref.value?.open(interviewGroup.value, students.value)
}

// 时间分配完毕 保存数据
const handleFinish = async (value: StudentVO[]) => {
  const data: InterviewGroupWithStudentSlotsSaveReqVO = {
    ...interviewGroup.value,
    students: value
  } as InterviewGroupWithStudentSlotsSaveReqVO
  if (interviewGroup.value?.id) {
    // 更新
    await InterviewGroupApi.updateInterviewGroupNew(data)
  } else {
    // 新增
    await InterviewGroupApi.createInterviewGroupNew(data)
  }

  message.success(t('common.operSuccess'))
  // 刷新列表
  await getList()
}

defineExpose({
  show
})
</script>
